<?php

/**
* Admin Form Library
*
*
*/
class AdminForm {

	var $_fieldset = '';
	var $_elements = array();
	var $_buttons = array();
	var $_values = array();
	var $_attributes = array();
	var $_objectId;
	var $_delete_url;
	var $_js;
	private $_header_text;

	private $CI;


	function __construct () {
		$this->CI = & get_instance();
		if (is_null($this->_objectId)){
			$this->_objectId = $this->CI->input->get_param('id',false);
		}
	}

	function set_detele_url($delete_url){
		$this->_delete_url = $delete_url;
		return $this;
	}

	function get_delete_url(){
		if (is_null($this->_delete_url)){
			$method = $this->CI->router->fetch_method();
			$methodArr = explode('_',$method);
			$current_method = $methodArr[count($methodArr)-1];
			$this->_delete_url = admin_url('*/*/delete_'.$current_method,array('id'=>$this->_objectId));
		}
		return $this->_delete_url;
	}

	function get_object_id(){
		return $this->_objectId;
	}

	function set_form_attributes($attributes = array()){
		$this->_attributes = $attributes;
		return $this;
	}

	function get_form_attribute($attribule){
		if (isset($this->_attributes[$attribule])){
			return $this->_attributes[$attribule];
		}
		return '';
	}

	function get_form_id(){
		if (($id = $this->get_form_attribute('id'))){
			return $id;
		}
		return 'edit_form';
	}

	function get_form_js_object(){
		return $this->get_form_id().'Form';
	}

	function set_header_text($header_text){
		$this->_header_text = $header_text;
		return $this;
	}

	function get_header_text(){
		if (is_null($this->_header_text)){
			if ($this->get_object_id() && is_array($this->get_values()) && count($this->get_values()) > 0){
				$this->_header_text = __("Edit '%s'",$this->_values['name']);
			}else{
				$this->_header_text = 'Add New';
			}
		}
		return $this->_header_text;
	}

	function add_button($button_id,$options = array()){
		$this->_buttons[$button_id] = array(
										'id'=>((isset($options['id'])?$options['id']:'id_'.random_string('numeric',16))),
										'class'=>(isset($options['class'])?$options['class'].' scalable':'scalable'),
										'onclick'=>(isset($options['onclick'])?$options['onclick']:''),
										'type'=>'button',
										'label'=>(isset($options['label'])?$options['label']:'')
									  );
	}

	function remove_button($button_id){
		if (array_key_exists($button_id,$this->_buttons)){
			unset($button_id);
		}
		return $this;
	}

	function set_values(array $value=array()){
		$this->_values = $value;
		return $this;
	}

	function get_values(){
		if (is_null($this->_values)){
			$this->_values = array();
		}
		return $this->_values;
	}

	function get_filed_value($filed){

		$values = $this->get_values();
		$_element_value = '';
		if (is_array($values) && count($values)>0){
			if (isset($values[$filed])){
				$_element_value = $values[$filed];
			}
		}
		return $_element_value;
	}
	/**
	 *
	 * Add filedset to form
	 * @param string $element_id
	 * @param array $config
	 */
	function add_filedset($element_id,$config){
		$this->_fieldset = $element_id;
		$this->_elements[$this->_fieldset] = $config;
		return $this;
	}

	function get_filedsets(){
		return $this->_fieldsets;
	}

	function unset_filedset($element_id){
		if (isset($this->_elements[$element_id])){
			unset($this->_elements[$element_id]);
		}
		return $this;
	}

	/**
	 *
	 * Add filed to Filedset
	 * @param string $element_id
	 * @param string $type
	 * @param array $config
	 */
	function add_filed($element_id,$type,$config){
		$options = array_merge($config,array('type'=>$type));
		$this->_add_filed($element_id,$options);
	}

	private function _add_filed($element_id, $config) {
		
		$this->_elements[$this->_fieldset][$element_id] = array(
			'label'=>(isset($config['label'])?$config['label']:''),
			'type'=>$config['type'],
			'name'=>$config['name'],
		    'onchange'=> (isset($config['onchange'])?$config['onchange']:''),
			'value'=>(isset($config['value'])?$config['value']:$this->get_filed_value($config['name'])),
			'values'=>(isset($config['values'])?$config['values']:array()),
			'id'=>(isset($config['id'])?$config['id']:$config['name']),
			'required'=>((isset($config['required']) && $config['required'] == true)?true:false)
		);
		//var_dump($this->_elements);
	}

	/**
	 * remove filed in fileset
	 */
	function unset_filed($element_id){
		foreach ($this->_elements as $filedset_id=>$element){
			foreach ($element as $key=>$config){
				if ($key == $element_id){
					unset($this->_elements[$filedset_id][$key]);
				}
			}
		}
		return $this;
	}

    function add_filed_js($element_id, $string_js = '') {
        $this->_js[$element_id] = $string_js;
    }
 
    function get_filed_js(){
        $js = '';
        if (isset($this->_js) && count($this->_js) > 0) {
            foreach ($this->_js as $key => $val) {
                $js .=  PHP_EOL . $val; 
            }
        }

        return $js;
	}
	/**
	* Display the form
	*
	* @return string Form HTML
	*/
	function to_html() {
		$this->add_button('back',array(
			'label'=>__('Back'),
			'class'=>'back',
			'onclick'=>'javascript:history.go(-1)'
		));
		$this->add_button('reset',array(
			'label'=>__('Reset'),
			'onclick'=>'setLocation(window.location.href)'
		));
//		if ($this->_objectId){
//			$this->add_button('detele',array(
//				'label'=>__('Delete'),
//				'class'=>'delete',
//				'onclick'=>'deleteConfirm(\''.__('Are you sure you want to do this?').'\',\''.$this->get_delete_url().'\')'
//			));
//		}
		$onsubmit = "";
		if ($this->get_form_attribute('onsubmit')) {
			$onsubmit = $this->get_form_attribute('onsubmit'). ";";	
		}

		$this->add_button('save',array(
			'label'=>'Save',
			'class'=>'save',
			'onclick'=> $onsubmit. ' '. $this->get_form_js_object().'.submit();',
		));

		$t = '';
		$return = '';

		$return .= '<div class="columns clr">'."\n";
		$return .='<div class="side-col">'."\n";
		$return .='<ul id="'.$this->get_form_id().'_tabs" class="tabs">'."\n";
		foreach ($this->_elements as $key=>$_fieldset){
			$return .='<li><a id="'.$this->get_form_id().'_tabs_group_'.$key.'" class="tab-item-link" href="javascript:void(0)" >'."\n";
				if (isset($_fieldset['legend'])){
					$return .= '<span>' .$_fieldset['legend']. '</span>'."\n";
				}
			$return .='</a></li>'."\n";
		}
//
		$return .='</ul>'."\n";
		$return .='</div>'."\n";
		$return .='<div class="main-col">'."\n";
		$return .='<div class="main-col-inner">'."\n";
		$return .='<div class="content-header clr">'."\n";
		$return .='<h3 >'.$this->get_header_text().'</h3>'."\n";
		if(count($this->_buttons)>0){
			//ksort($this->_buttons);
			$return .='<p class="form-buttons">'."\n";
			foreach ($this->_buttons as $_button){
				$return .= '<button id="'.$_button['id'].'" title="'.$_button['label'].'" class="'.$_button['class'].'" type="'.$_button['type'].'" onclick="'.$_button['onclick'].'"><span >'.$_button['label'].'</span></button>'."\n";
			}
			$return .= '</p>'."\n";
		}
		$return .='</div>'."\n";
		$return .='<div class="entry-edit">'."\n";

		
		
		$return .='<form id="'.$this->get_form_id().'" class="form" action="'.$this->get_form_attribute('action').'" enctype="'.($this->get_form_attribute('enctype')).'" method="'.(($this->get_form_attribute('method')!='')?$this->get_form_attribute('method'):'post').'">'."\n";
		$return .='<div><input type="hidden" value="'.$this->CI->security->get_csrf_hash().'" name="'.$this->CI->security->get_csrf_token_name().'"></div>'."\n";
		$i=0;
		foreach ($this->_elements as $key=>$_fieldset) {
			$style = (++$i==1)?'':'display:none';
			$return .='<div id="'.$this->get_form_id().'_tabs_group_'.$key.'_content" class="tab_content" style="'.$style.'">'."\n";
			$return .='<div class="entry-edit-head clr"><h4>'.(isset($_fieldset['legend'])?$_fieldset['legend']:'').'</h4></div>'."\n";
			$return .= '<div id="" class="fieldset">'."\n";
			$return .='<div class="hor-scroll">'."\n";
			$return .= '<table class="form-list" cellspacing="0">'."\n";
			foreach ($_fieldset as $_elements){
				if (is_array($_elements) && count($_elements)>0){
					$return .="<tr>\n";
					if ($_elements['type'] == 'hidden'){
						$return .="<td colspan=\"2\" class=\"hidden\">\n<input type=\"hidden\" name=\"{$_elements['name']}\" value=\"{$_elements['value']}\"></td>\n";
					}else{
						$return .="<td class=\"label\">";
						$return .= "<label for=\"{$_elements['id']}\">{$_elements['label']}";
						if ($_elements['required']){
							$return .=" <span class=\"required\">*</span>";
						}
						$return .="</label>\n";
						$return .="</td>\n";
						$return .="<td class=\"value\">\n";
						$class = "";
						switch ($_elements['type']){
							case 'alias':
								if ($_elements['required']){
									$class="required-entry validate-alias";
								}
								$return .="<input id=\"{$_elements['id']}\" class=\"text {$class}\" type=\"text\" value=\"{$_elements['value']}\" name=\"{$_elements['name']}\"  />";

							break;
							case 'text':
								if ($_elements['required']){
									$class="required-entry";
								}
								$return .="<input id=\"{$_elements['id']}\" class=\"text {$class}\" type=\"text\" value=\"{$_elements['value']}\" name=\"{$_elements['name']}\"  />";
							break;
							case 'password':
								if ($_elements['required']){
									$class ="required-entry";
								}
								$return .="<input id=\"{$_elements['id']}\" class=\"text {$class}\" type=\"text\" value=\"{$_elements['value']}\" name=\"{$_elements['name']}\"  />";
							break;
							case 'select':
								if ($_elements['required']){
									$class ="required-entry";
								}

								$onchange = '';
								if (isset($_elements['onchange'])) {
								    $onchange = " onchange='{$_elements['onchange']}' ";
								}

								$return .="<select id=\"{$_elements['id']}\" name=\"{$_elements['name']}\" class=\"select {$class}\" {$onchange}>\n";

									$return .="<option value=\"\"></option>\n";
									if (is_array($_elements['values']) && count($_elements['values'] > 0)){

										foreach ($_elements['values'] as $_value=>$_label){
											$slected = "";
											if ($_elements['value'] == $_value){
												$slected = "selected=\"selected\"";
											}
											$return .="<option value=\"{$_value}\" $slected>{$_label}</option>\n";
										}
									}
								$return .="</select>\n";

							break;

							case 'select-multi':

								if ($_elements['required']){
									$class ="required-entry";
								}

								$option_right = "";
								$option_left = "";

								if (is_array($_elements['values']) && count($_elements['values'] > 0)) {
									foreach ($_elements['values'] as $_value=>$_label){

										$flg_right = false;
										foreach ($_elements['value'] as $value) {
											if ($value == $_value) {
												$option_right .="<option value=\"{$_value}\" $slected>{$_label}</option>\n";
												$flg_right = true;
											}
										}

										if (!$flg_right) {
											$option_left .="<option value=\"{$_value}\" $slected>{$_label}</option>\n";
										}
									}
								}

								$select_left ="<select id=\"left_{$_elements['id']}\" name=\"left_{$_elements['name']}\" class=\"select {$class}\" size=\"10\" multiple>\n";
								$select_left .= $option_left;
								$select_left .="</select>\n";

								$select_right ="<select id=\"right_{$_elements['id']}\" name=\"{$_elements['name']}\" class=\"select {$class}\" size=\"10\" multiple>\n";
								$select_right .= $option_right;	
								$select_right .="</select>\n";

								$return .="
								<table border=\"0\">
									<tr>
										<td rowspan=\"3\" align=\"right\">
											{$select_left}
										</td>
										<td align=\"left\">
											&nbsp;
										</td>
										<td align=\"left\">
											&nbsp;
										</td>
										<td rowspan=\"3\" align=\"left\">
											{$select_right}
										</td>
									</tr>
									<tr>
										<td align=\"left\">
											&nbsp;
										</td>
										<td align=\"left\">
											<label>
											<input name=\"btnRight\" type=\"button\" id=\"btnRight\" value=\"&gt;&gt;\" onclick=\"javaScript:moveToRightOrLeft(1, 'left_{$_elements['id']}', 'right_{$_elements['id']}');\">
											</label>
										</td>
									</tr>
									<tr>
										<td align=\"left\">
											&nbsp;
										</td>
										<td align=\"left\">
											<label>
											<input name=\"btnLeft\" type=\"button\" id=\"btnLeft\" value=\"&lt;&lt;\" onclick=\"javaScript:moveToRightOrLeft(2, 'left_{$_elements['id']}', 'right_{$_elements['id']}');\">
											</label>
										</td>
									</tr>
								</table>";

							break;

							case 'multiple-select':
								if ($_elements['required']){
									$class ="required-entry";
								}

								/*$return .= "<select id=\"{$_elements['name']}\" multiple=\"multiple\" name=\"{$_elements['name']}[]\" {$class} title=\"chọn\">";
								if (is_array($_elements['values']) && count($_elements['values'] > 0)) {
									foreach ($_elements['values'] as $_value=>$_label) {
										$return .="<option value=\"{$_value}\" $slected>{$_label}</option>\n";
									}
								}
								$return .= '</select>';*/

								break;

							case 'image':
							case 'file':
								if ($_elements['required']){
									$class ="required-entry";
								}
								if ($_elements['type']=="image" && $_elements['value'] !=""){
									$return .='<a onclick="imagePreview(\''.$_elements['id'].'_image\'); return false;" href="'.base_url($_elements['value']).'"><img class="small-image-preview v-middle" width="50" height="50" id="'.$_elements['id'].'_image" src="'.$_elements['value'].'" /></a> ';
								}
								$return .="<input type=\"file\" class=\"{$class}\" id=\"{$_elements['id']}\" name=\"{$_elements['name']}\" />";
								if ($_elements['type']=="image" && $_elements['value'] !=""){
									$return .="<input type=\"hidden\" id=\"{$_elements['id']}_value\" name=\"{$_elements['name']}_value\" value=\"{$_elements['value']}\"/>\n";
								}
								if ($_elements['type'] =="file" && $_elements['value'] !=""){
									$return .="<br/>\n<strong>Uploaded: </strong>".$_elements['value']."<br/>\n";
								}
								if ($_elements['value'] !=""){
								$return .="<span class=\"delete-image\">\n<input type=\"checkbox\" name=\"{$_elements['name']}_delete\" id=\"{$_elements['id']}_delete\" />\n"
									."<label for=\"{$_elements['id']}_delete\">".__('Delete File')."</label>"
									."</span>\n";
								}
							break;
							case 'radio':
								if ($_elements['required']){
									$class = "required-entry";
								}
								$return .="";
							break;
							case 'date':
								if ($_elements['required']){
									$class="required-entry";
								}
								$this->CI->load->library('calendarjs');
								$return .="<input id=\"{$_elements['id']}\" class=\"text {$class}\" style=\"width:110px !important;\" type=\"text\" value=\"{$_elements['value']}\" name=\"{$_elements['name']}\"  />";
								$return .=" <img id=\"{$_elements['id']}_trig\" class=\"v-middle\" title=\"Select Date\" alt=\"\" src=\"".base_url('templates/backend/images/grid-cal.gif')."\">";
								$js = "Calendar.setup({\ninputField: \"{$_elements['id']}\",\nifFormat: \"%Y-%m-%d\",\nshowsTime: false,\nbutton: \"{$_elements['id']}_trig\",\nalign: \"Bl\",\nsingleClick : true\n}); ";
								$return .= jsScript($js);
							break;
							case 'checkbox':
							    //<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
							    if (is_array($_elements['values']) && count($_elements['values'] > 0)){
							        foreach ($_elements['values'] as $_value=>$_label){
							            $slected = "";
							            if ($_elements['value'] == $_value){
							                $slected = "checked";
							            }
							            $return .="<input type=\"checkbox\" value=\"{$_value}\" name=\"{$_elements['name']}\" $slected>{$_label}<br/>";
							        }
							    }
							break;
							case 'textarea':
								$return .= "<textarea id=\"{$_elements['id']}\" name=\"{$_elements['name']}\" class=\"textarea\">{$_elements['value']}</textarea>\n";

							break;
							case 'editor':
								$this->CI->load->library('editor');
								$this->CI->editor->init($_elements['name']);
								$return .= "<textarea id=\"{$_elements['id']}\" name=\"{$_elements['name']}\" class=\"textarea mce_editable\" style=\"height:400px\">{$_elements['value']}</textarea>\n";
							break;
						}
						$return .="</td>\n";
					}
					$return .="</tr>\n";
				}
			}
			$return .= '</table>'."\n";
			$return .='</div>'."\n";
			$return .= '</div>'."\n";
			$return .= '</div>'."\n";
			}
			$return .= '</form>'."\n";
			$return .='</div>'."\n";
			$return .='</div>'."\n";
			$return .='</div>'."\n";
			$return .='</div>'."\n";
			$return .='<script type="text/javascript">'."\n".'//<![CDATA[ '."\n".' '.$this->get_form_js_object().' = new varienForm(\''.$this->get_form_id().'\',\'\') ; '."\n".'//]]>'."\n".'</script>'."\n";

		return $return;
	}

	
}